<template>
  <div class="app-container">
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="相册底片" name="0" />
      <el-tab-pane label="已选照片" name="1" />
      <el-tab-pane label="精修照片" name="2" />
    </el-tabs>

    <div>
      <el-dialog
        :visible.sync="dialogVisible"
        title="上传中"
        width="30%"
        @close="handleDialogClose"
      >
        <el-progress :percentage="uploadPercentage"></el-progress>
        <el-button type="text" class="cancel-all-btn" @click="cancelAllUpload"
          >全部取消</el-button
        >
        <el-scrollbar wrap-class="scrollbar-wrapper">
          <div v-for="(file, index) in uploadingFiles" :key="file.uid">
            <div class="file-item">
              <span class="file-name">{{ file.name }}</span>
              <div class="progress-container">
                <el-progress :percentage="file.percent"></el-progress>
                <el-button
                  type="text"
                  @click="cancelUpload(file)"
                  class="cancel-btn"
                  icon="el-icon-close"
                >
                </el-button>
              </div>
            </div>
            <!-- 添加浅色分割线，最后一个文件不添加分割线 -->
            <el-divider
              v-if="index < uploadingFiles.length - 1"
              class="file-divider"
            ></el-divider>
          </div>
        </el-scrollbar>
      </el-dialog>

      <!--       <div class="photo-upload-card">
        <el-upload
          ref="upload"
          :action="`${UPLOAD_FILE_URL}/admin/show/fileUpload`"
          :on-success="handleSuccess"
          :on-progress="handleProgress"
          :before-upload="beforeUpload"
          :file-list="fileList"
          :show-file-list="false"
          :disabled="showUpload"
          multiple
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </div> -->
    </div>
    <div class="grid">
      <div v-for="image in uploadedImages" :key="image.id" class="grid-item">
        <img :src="image.imgUrl" alt="照片" />
      </div>
    </div>
  </div>
</template>

<script>
import AlbumApi from '@/api/photo/album'
import { UPLOAD_FILE_URL } from '@/api/path-to-config/config'
import Masonry from 'masonry-layout'

export default {
  data() {
    return {
      // 接口API地址
      UPLOAD_FILE_URL: UPLOAD_FILE_URL,
      activeName: '0', // 0-底片，1-已选，2-精修
      allImgList: [],
      selectImgList: [],
      modifyImgList: [],
      albumId: '',
      uploadingFiles: [],
      uploadedImages: [],
      dialogVisible: false,
      uploadPercentage: 0,
      fileList: [],
      isHovered: -1, // 当前悬停卡片的索引，-1 表示没有卡片悬停
      showUpload: false
    }
  },

  // 生命周期函数：内存准备完毕，页面尚未渲染
  created() {
    if (this.$route.params && this.$route.params.id) {
      if (this.$route.params && this.$route.params.id) {
        this.albumId = this.$route.params.id
        this.fetchData(this.albumId)
      } else {
        this.$router.push({ path: '/album/list' })
      }
    }
  },
  methods: {
    // 加载banner列表数据
    fetchData(id) {
      AlbumApi.getById(id).then((response) => {
        console.log(response)
        this.AlbumInfo = response.data
        // 图片回显
        this.allImgList = this.AlbumInfo.allImgList
        this.selectImgList = this.AlbumInfo.selectImgList
        this.modifyImgList = this.AlbumInfo.modifyImgList
        this.uploadedImages = this.allImgList
        this.intiMasonry()
      })
    },
    handleClick() {
      console.log(this.activeName)
      if (this.activeName === '1') {
        this.uploadedImages = this.selectImgList
        this.showUpload = true
      } else if (this.activeName === '2') {
        this.uploadedImages = this.modifyImgList
        this.showUpload = false
      } else {
        this.uploadedImages = this.allImgList
        this.showUpload = false
      }
    },
    intiMasonry() {
      console.log(1111)
      // 如果所有图片加载完，调用实现瀑布流代码
      var elem = document.querySelector('.photo-wall')
      var msnry = new Masonry(elem, {
        // options
        itemSelector: '.photo-card',
        percentPosition: true,
        columnWidth: '.photo-card'
      })
      var msnry = new Masonry('.photo-card', {
        // options...
      })
    },
    addImg(imgName, imgUrl) {
      let obj = new Object()
      obj.imgUrl = imgUrl
      obj.imgName = imgName
      obj.albumId = this.albumId
      obj.status = this.activeName
      AlbumApi.saveImg(obj).then((response) => {
        console.log(response)
      })
    },
    beforeUpload(file) {
      this.uploadingFiles.push(file)
      this.dialogVisible = true
      return true // 继续上传
    },
    handleSuccess(response, file) {
      console.log(file)
      const index = this.uploadingFiles.findIndex((f) => f.uid === file.uid)
      if (index !== -1) {
        this.uploadingFiles.splice(index, 1)
      }

      this.uploadedImages.push({
        id: this.uploadedImages.length + 1,
        name: file.name,
        url: response.data // 假设服务器返回的是一个包含图片地址的对象
      })
      // 照片入库
      this.addImg(file.name, response.data)

      if (this.uploadingFiles.length === 0) {
        this.dialogVisible = false
        this.uploadPercentage = 0
      }
    },
    handleProgress(event, file, fileList) {
      if (event.percent) {
        this.uploadPercentage = event.percent
      }
      // 更新弹框中每个文件的进度信息
      const index = this.uploadingFiles.findIndex((f) => f.uid === file.uid)
      if (index !== -1) {
        this.$set(this.uploadingFiles, index, {
          ...file,
          percent: event.percent
        })
      }
    },
    cancelUpload(file) {
      const index = this.uploadingFiles.findIndex((f) => f.uid === file.uid)
      if (index !== -1) {
        // 调用 Element UI 的 abort 方法取消上传
        this.$refs.upload.abort(file)

        // 移除取消的文件
        this.uploadingFiles.splice(index, 1)
        this.uploadPercentage = 0 // 重置进度

        // 如果没有文件在上传了，关闭弹框
        if (this.uploadingFiles.length === 0) {
          this.dialogVisible = false
        }
      }
    },
    cancelAllUpload() {
      // 取消全部上传
      this.uploadingFiles.forEach((file) => {
        this.$refs.upload.abort(file)
      })

      // 清空文件列表
      this.uploadingFiles = []
      this.uploadPercentage = 0
      this.dialogVisible = false
    },
    handleDialogClose() {
      // 处理弹框关闭事件，例如清理数据
      this.uploadingFiles = []
      this.uploadPercentage = 0
    },
    deleteImage(index, imageId) {
      // 处理删除图片的逻辑，例如调用 API 或者从数据中移除图片
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // promise
          // 点击确定，远程调用ajax
          return AlbumApi.removeImg(this.albumId, imageId)
        })
        .then((response) => {
          this.uploadedImages.splice(index, 1)
          if (response.code) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>

<style>
/* 文件卡片样式 */
.file-card {
  margin-bottom: 10px;
}

/* 文件进度容器样式 */
.progress-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 取消按钮样式 */
.cancel-btn {
  color: #ff4500; /* 红色 */
  cursor: pointer;
}

/* 全部取消按钮样式 */
.cancel-all-btn {
  margin-bottom: 10px;
  color: #ff4500; /* 红色 */
  cursor: pointer;
}

/* 弹框滚动条样式 */
.scrollbar-wrapper {
  height: 200px; /* 设置适当的高度 */
  overflow-y: auto;
}
/* 文件项样式 */
.file-item {
  margin-bottom: 10px;
}

/* 文件名样式 */
.file-name {
  font-weight: bold;
}

/* 文件项和浅色分割线之间的距离 */
.file-divider {
  margin: 10px 0;
}
/* 上传按钮的样式与照片卡片相同 */
.photo-upload-card {
  position: relative;
  border: 1px solid #ccc;
  border-radius: 5px;
  overflow: hidden;
  width: 100%; /* 适当调整按钮所在卡片的宽度百分比 */
  height: 0; /* 初始高度为0，以便使用百分比来计算 */
  padding-top: 100%; /* 使用padding-top来设置高度为宽度的百分比，实现自适应效果 */
  margin: 0; /* 确保按钮卡片与下一个照片卡片之间没有额外的间距 */
  font-size: 6em; /* 使用 em 或 rem 设置相对大小 */
}
.el-icon-plus {
  font-size: 100%; /* 适当调整图标的大小 */
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #a5a5a5; /* 适当调整图标的颜色 */
}
.grid {
  max-width: 1200px;
  margin: 0 auto;
}

.grid:after {
  content: '';
  display: block;
  clear: both;
}

.grid-item {
  width: 23%;
  padding: 10px;
  float: left;
  margin: 1%;
  background: #0d8fdb;
  border: 2px solid #333;
  border-radius: 5px;
  box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
}

.grid-item img {
  max-width: 100%;
  height: auto;
  display: block;
}

@media (max-width: 768px) {
  .grid-item {
    width: 48%;
  }
}

@media (max-width: 480px) {
  .grid-item {
    width: 98%;
  }
}
</style>
